package worldutils.huntgame.Utils;

import org.bukkit.Bukkit;
import org.bukkit.Location;
import org.bukkit.Material;
import org.bukkit.World;
import org.bukkit.block.Block;

import java.util.HashSet;
import java.util.Random;
import java.util.Set;

public class RandomSpawnUtils {
    private static final Random random = new Random();

    // 获取随机位置方法一
    public static Location getRandomLocation(World world, double x0, double z0) {
        Location location = null;

        while (location == null) {
            // 在半径30格范围内获取随机位置
            double x = x0 + (random.nextDouble() * 60 - 30);
            double z = z0 + (random.nextDouble() * 60 - 30);
            double y = world.getHighestBlockYAt((int) x, (int) z) + 1;

            location = new Location(world, x, y + 1, z);

            if (!isSuitableLocation(location)) {
                location = null;
                x0 += 100; // 如果不符合条件，则将中心点X坐标增加100
            }
        }

        return location;
    }

    // 获取随机位置方法二
    public static Location getRandomLocationTwo(World world, Location previousLocation) {
        double x0 = previousLocation.getX();
        double z0 = previousLocation.getZ();

        Location location = null;

        while (location == null) {
            // 在半径20格范围内获取随机位置
            double x = x0 + (random.nextDouble() * 40 - 20);
            double z = z0 + (random.nextDouble() * 40 - 20);
            double y = world.getHighestBlockYAt((int) x, (int) z); // 获取地面最高点

            location = new Location(world, x, y + 1, z);

            if (!isSuitableLocation(location)) {
                location = null;
            }
        }

        return location;
    }

    // 判断位置是否适合玩家出生
    private static boolean isSuitableLocation(Location location) {
        World world = location.getWorld();
        if (world == null) return false;

        Block feetBlock = world.getBlockAt(location);
        Block headBlock = world.getBlockAt(location.clone().add(0, 1, 0));
        Block aboveHeadBlock = world.getBlockAt(location.clone().add(0, 2, 0));
        Block belowFeetBlock = world.getBlockAt(location.clone().add(0, -1, 0));

        // 检查玩家四周方块
        Block northBlock = world.getBlockAt(location.clone().add(0, 1, -1));
        Block southBlock = world.getBlockAt(location.clone().add(0, 1, 1));
        Block eastBlock = world.getBlockAt(location.clone().add(1, 1, 0));
        Block westBlock = world.getBlockAt(location.clone().add(-1, 1, 0));

        // 确保脚下不允许有水，脚下方块不能是空气，头顶三格必须为空，四周也必须为空
        return belowFeetBlock.getType() != Material.WATER &&
                feetBlock.getType() != Material.AIR &&
                headBlock.getType() == Material.AIR &&
                aboveHeadBlock.getType() == Material.AIR &&
                northBlock.getType() == Material.AIR &&
                southBlock.getType() == Material.AIR &&
                eastBlock.getType() == Material.AIR &&
                westBlock.getType() == Material.AIR;
    }
}
